package cn.neusoft.baibang.service.impl;

import cn.neusoft.baibang.constants.RedisCourseConstant;
import cn.neusoft.baibang.domain.ProductType;
import cn.neusoft.baibang.mapper.ProductTypeMapper;
import cn.neusoft.baibang.service.IProductTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzm
 * @since 2022-12-10
 */
@Service
public class ProductTypeServiceImpl extends ServiceImpl<ProductTypeMapper, ProductType> implements IProductTypeService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private ProductTypeMapper productTypeMapper;
    @Override
    @Cacheable(cacheNames = RedisCourseConstant.COURSE_TYPE_TREE_DATA_CACHE_NAMES,key = RedisCourseConstant.COURSE_TYPE_TREE_DATA_CACHE_KEY)
    public List<ProductType> getTreeDate1() {
        return getProductType();
    }

    private List<ProductType> getProductType() {
        List<ProductType> productTypes = productTypeMapper.selectList1();
        Map<Long, ProductType> productTypeMap = productTypes.stream().collect(Collectors.toMap(ProductType::getId, productType -> productType));
        List<ProductType> treeDate = new ArrayList<>();
        productTypes.forEach(productType -> {
            // 2.1 找到父级
            if (productType.getPid()!=null&&productType.getPid().intValue()==0){
                treeDate.add(productType);
            }else {
                // 2.2 若自己不是顶级 那么放入到新的集合中
                ProductType parentProductType = productTypeMap.get(productType.getPid());
                if (parentProductType != null){
                    parentProductType.getChildren().add(productType);
                }
            }
        });
        System.out.println(treeDate);
        return treeDate;
    }

    @Override
    @CacheEvict(cacheNames = RedisCourseConstant.COURSE_TYPE_TREE_DATA_CACHE_NAMES,key = RedisCourseConstant.COURSE_TYPE_TREE_DATA_CACHE_KEY)
    public boolean insert(ProductType entity) {
        return super.insert(entity);
    }
    @Override
    @CacheEvict(cacheNames = RedisCourseConstant.COURSE_TYPE_TREE_DATA_CACHE_NAMES,key = RedisCourseConstant.COURSE_TYPE_TREE_DATA_CACHE_KEY)
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }
    @Override
    @CacheEvict(cacheNames = RedisCourseConstant.COURSE_TYPE_TREE_DATA_CACHE_NAMES,key = RedisCourseConstant.COURSE_TYPE_TREE_DATA_CACHE_KEY)
    public boolean updateById(ProductType entity) {
        return super.updateById(entity);
    }

}
